package com.markerhub.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.markerhub.common.lang.Result;
import com.markerhub.entity.InspectionPlan;
import com.markerhub.entity.InspectionTask;
import com.markerhub.service.InspectionTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Arrays;

/**
 * 巡检任务Controller
 */
@Api(tags = "巡检任务管理")
@RestController
@RequestMapping("/api/inspection-task")
public class InspectionTaskController extends BaseController {

    @Autowired
    private InspectionTaskService inspectionTaskService;

    /**
     * 分页获取巡检任务列表
     */
    @ApiOperation(value = "分页获取巡检任务列表", notes = "根据条件分页查询巡检任务列表")
    @PreAuthorize("hasAuthority('inspection:task:list')")
    @GetMapping("/list")
    public Result list(InspectionTask task) {
        // 使用BaseController中的getPage()方法获取分页参数
        Page<InspectionTask> page = getPage();
        // 构建查询条件
        QueryWrapper<InspectionTask> wrapper = new QueryWrapper<>();
        if (task.getTaskName() != null && !task.getTaskName().isEmpty()) {
            wrapper.like("task_name", task.getTaskName());
        }
        if (task.getStatus() != null) {
            wrapper.eq("status", task.getStatus());
        }
        // 按创建时间倒序排序
        wrapper.orderByDesc("created");
        // 执行分页查询
        Page<InspectionTask> pageData = inspectionTaskService.page(page, wrapper);
        return Result.succ(200, "获取巡检任务列表成功", pageData);
    }

    /**
     * 查询巡检任务 - 分页
     */
    @ApiOperation(value = "查询巡检任务", notes = "根据条件查询巡检任务信息，支持分页")
    @PreAuthorize("hasAuthority('inspection:task:query')")
    @GetMapping("/query")
    public Result query(InspectionTask task) {
        return list(task);
    }

    /**
     * 根据ID获取巡检任务详情
     */
    @ApiOperation(value = "获取巡检任务详情", notes = "根据ID获取指定巡检任务的详细信息")
    @PreAuthorize("hasAuthority('inspection:task:detail')")
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable Long id) {
        Map<String, Object> task = inspectionTaskService.getTaskByIdWithDevice(id);
        return Result.succ(task);
    }

    /**
     * 创建巡检任务
     */
    @ApiOperation(value = "新增巡检任务", notes = "新增巡检任务信息")
    @PreAuthorize("hasAuthority('inspection:task:add')")
    @PostMapping("/add")
    public Result add(@Validated @RequestBody InspectionTask task) {
        task.setCreated(new Date());
        task.setUpdated(new Date());
        boolean saved = inspectionTaskService.save(task);
        return saved ? Result.succ(200, "创建巡检任务成功", task) : Result.fail("创建巡检任务失败");
    }

    /**
     * 更新巡检任务
     */
    @ApiOperation(value = "更新巡检任务", notes = "更新指定巡检任务的详细信息")
    @PreAuthorize("hasAuthority('inspection:task:update')")
    @PutMapping("/update")
    public Result update(@Validated @RequestBody InspectionTask task) {
        task.setUpdated(new Date());
        boolean updated = inspectionTaskService.updateById(task);
        return updated ? Result.succ(200, "更新巡检任务成功", task) : Result.fail("更新巡检任务失败");
    }

    /**
     * 删除单个巡检任务
     */
    @ApiOperation(value = "删除巡检任务", notes = "删除指定ID的巡检任务信息")
    @PreAuthorize("hasAuthority('inspection:task:delete')")
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Long id) {
        boolean deleted = inspectionTaskService.removeById(id);
        return deleted ? Result.succ(200, "删除巡检任务成功", null) : Result.fail("删除巡检任务失败");
    }

    /**
     * 批量删除巡检任务
     */
    @ApiOperation(value = "批量删除巡检任务", notes = "批量删除多个巡检任务信息")
    @PreAuthorize("hasAuthority('inspection:task:delete')")
    @DeleteMapping("/delete")
    public Result delete(@RequestBody Long[] ids) {
        boolean deleted = inspectionTaskService.removeByIds(Arrays.asList(ids));
        return deleted ? Result.succ(200, "批量删除巡检任务成功", null) : Result.fail("批量删除巡检任务失败");
    }

    /**
     * 分配巡检任务
     */
    @ApiOperation(value = "分配任务", notes = "为巡检任务分配执行人")
    @PreAuthorize("hasAuthority('inspection:task:assign')")
    @PutMapping("/assign")
    public Result assign(@RequestBody TaskAssignDto data) {
        InspectionTask task = inspectionTaskService.getById(data.getTaskId());
        if (task == null) {
            return Result.fail("巡检任务不存在");
        }
        
        task.setAssigneeId(data.getAssigneeId());
        task.setUpdated(new Date());
        task.setStatus(2); // 2:执行中
        
        boolean updated = inspectionTaskService.updateById(task);
        return updated ? Result.succ(200, "任务分配成功", task) : Result.fail("任务分配失败");
    }

    /**
     * 更新任务状态
     */
    @ApiOperation(value = "更新任务状态", notes = "更新巡检任务的状态")
    @PreAuthorize("hasAuthority('inspection:task:status')")
    @PutMapping("/status")
    public Result updateStatus(@RequestBody TaskStatusDto data) {
        InspectionTask task = inspectionTaskService.getById(data.getTaskId());
        if (task == null) {
            return Result.fail("巡检任务不存在");
        }
        
        task.setStatus(data.getStatus());
        task.setUpdated(new Date());
        
        // 如果任务完成，设置完成时间
        if (3 == data.getStatus()) {
            task.setEndTime(new Date());
        }
        
        boolean updated = inspectionTaskService.updateById(task);
        return updated ? Result.succ(200, "任务状态更新成功", task) : Result.fail("任务状态更新失败");
    }

    // 辅助DTO类
    public static class TaskAssignDto {
        private Long taskId;
        private Long assigneeId;

        public Long getTaskId() {
            return taskId;
        }

        public void setTaskId(Long taskId) {
            this.taskId = taskId;
        }

        public Long getAssigneeId() {
            return assigneeId;
        }

        public void setAssigneeId(Long assigneeId) {
            this.assigneeId = assigneeId;
        }
    }

    public static class TaskStatusDto {
        private Long taskId;
        private Integer status;

        public Long getTaskId() {
            return taskId;
        }

        public void setTaskId(Long taskId) {
            this.taskId = taskId;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }
}